/*
  * Mirante Tecnologia
  * Copyright 2010, Mirante Informatica LTDA, 
  * and individual contributors as indicated by the @authors tag
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
package com.miranteinfo.seam.framework.action.interceptor;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.jboss.seam.annotations.intercept.AroundInvoke;
import org.jboss.seam.annotations.intercept.Interceptor;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.intercept.InvocationContext;

import com.miranteinfo.seam.framework.service.exception.BusinessException;
import com.miranteinfo.seam.framework.service.exception.BusinessException.Message;

/**
 * Interceptor criado para interceptar todas as excecoes do tipo {@link BusinessException}
 * que sao lancadas e adicionar ao {@link FacesMessages} as mensagens passadas.
 * 
 * @author lucas lins
 *
 */
@Interceptor(around = ConversationInterceptorImpl.class)
public class BusinessMessageInterceptorImpl {
	
	@AroundInvoke
	public Object intercept(InvocationContext invocation) throws Exception {
		try{
			return invocation.proceed();
		}catch(BusinessException e){
			displayMessages(e);
			return null;
		}
	}
	
	/**
	 * Adiciona as mensagens de regra de neogcio no {@link FacesMessages}.
	 * 
	 * @param e
	 */
	public void displayMessages(BusinessException e){
		FacesMessages facesMessages = FacesMessages.instance();
		ResourceBundle bundle = org.jboss.seam.core.ResourceBundle.instance();
		
		for(Message msg : e.getErrors()){
			try{
				bundle.getString(msg.getMessage());
				facesMessages.addFromResourceBundle(msg.getSeverity(), msg.getMessage(), msg.getParams());
			}catch(MissingResourceException ex){
				facesMessages.add(msg.getSeverity(), msg.getMessage(), msg.getParams());
			}
		}
	}
}
